package cre.sample.test.httpclient;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;

/**
 * @Author penglai
 * @Date 2016/10/4.
 */
public class HttpUtils {

    public static String get(String url) {
        String result = null;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();

            result = EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return result;
    }

    public static long download(String url, String filePath, String fileName) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpRequestBase httpRequest = new HttpGet(url);

        CloseableHttpResponse httpResponse = null;
        try {
            httpResponse = httpClient.execute(httpRequest);
            HttpEntity entity = httpResponse.getEntity();

            InputStream inputStream = entity.getContent();
            File dir = new File(filePath);
            if (dir.exists()) {
                dir.delete();
            } else {
                dir.mkdirs();
            }

            File file = new File(dir, fileName);
            FileOutputStream outputStream = new FileOutputStream(file);
            IOUtils.copy(inputStream, outputStream);
            return file.length();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
        }
        return 0;
    }

}
